class Feed < ActiveRecord::Base  
  has_and_belongs_to_many :feeds, 
    :join_table => 'feeds_links', 
    :association_foreign_key => 'destination_id', 
    :foreign_key => 'source_id'
    
  validates_presence_of :name, :message => "required"
  validates_uniqueness_of :name, :message => "already exists"
  
  def data
    require "rexml/document"
    require "icalendar"
    
    if File.exist? feed_filename
      unless self[:kind]=="ical"
        REXML::Document.new File.open(feed_filename)
      else
        Icalendar.parse(File.open(feed_filename)).first
      end
    else
      update_feed_data
    end
  end
  
  def feed_filename
    File.join(ENV["tmp_feeds_path"],self[:url][7..-1].tr("/?=&","_"))
  end
  
  def update_feed_data
    if self[:url]
      require "rexml/document"
      require "net/http"
      require "uri"
      
      uri = URI.parse(self[:url])
      
      begin
        res = Net::HTTP.start(uri.host, uri.port) {|http| http.get(uri.path,{"Accept" => "text/xml,application/xml,*/*;q=0.5","Accept-Charset" => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"})}
        self[:status] = res.code
        self[:kind]   = feed_filename.match(/\.ics$/) ? "ical" : "atom"
        self.save
      rescue
        self[:status] = nil
        self.save
      end
  
      case res
        when Net::HTTPSuccess
          unless self[:kind]=="ical"
            doc = REXML::Document.new res.body
            doc.root.delete_attribute("xmlns") if doc.root.attributes["xmlns"]
            open(feed_filename,"wb") { |f| f.write(doc.to_s) }
          else
            open(feed_filename,"wb") { |f| f.write(res.body) }
          end

          data
        else
          # do some error handling here
          res.error!
      end
    end
  end
end
